package com.yiwenup.leetcode.offer;

import com.yiwenup.leetcode.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof/
 **/
public class No032 {

    /**
     * 执行用时：1 ms, 在所有 Java 提交中击败了95.35%的用户
     * 内存消耗：38.7 MB, 在所有 Java 提交中击败了32.29%的用户
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) return new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int count = 1;
        int nextCount = 0;
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> list =  new ArrayList<>();
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            list.add(node.val);
            count--;
            if (node.left != null) {
                queue.offer(node.left);
                nextCount++;
            }
            if (node.right != null) {
                queue.offer(node.right);
                nextCount++;
            }
            if (count == 0) {
                res.add(new ArrayList<>(list));
                list.clear();
                count = nextCount;
                nextCount = 0;
            }
        }

        return res;
    }

    /**
     * 执行用时：1 ms, 在所有 Java 提交中击败了95.35%的用户
     * 内存消耗：38.7 MB, 在所有 Java 提交中击败了21.60%的用户
     */
    public List<List<Integer>> levelOrder2(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();

        if (root != null) queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<Integer>();
            for(int i = queue.size(); i > 0; i--) {
                TreeNode node = queue.poll();
                list.add(node.val);
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            res.add(list);
        }

        return res;
    }
}
